package com.example.baseweb.service.impl;

import com.example.baseweb.common.PageResponse;
import com.example.baseweb.dto.OrderInfoDTO;
import com.example.baseweb.entity.OrderInfo;
import com.example.baseweb.repository.OrderInfoRepository;
import com.example.baseweb.service.OrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl implements OrderInfoService {
    @Autowired
    private OrderInfoRepository orderInfoRepository;

    @Override
    public OrderInfo findById(Long id) {
        return orderInfoRepository.findById(id).orElse(null);
    }

    @Override
    public OrderInfo save(OrderInfo orderInfo) {
        return orderInfoRepository.save(orderInfo);
    }

    @Override
    public void refundOrder(String orderNo) {
        OrderInfo order = orderInfoRepository.findByOrderNo(orderNo);
        if (order != null && !"REFUNDED".equals(order.getStatus())) {
            order.setStatus("REFUNDED");
            order.setRefundTime(LocalDateTime.now());
            orderInfoRepository.save(order);
        }
    }

    @Override
    public OrderInfo findByOrderNo(String orderNo) {
        return orderInfoRepository.findByOrderNo(orderNo);
    }
    
    @Override
    public PageResponse<OrderInfoDTO> findOrderPage(int page, int size, String orderNo, String userId, String userName, String status, String mealType, String menuDate, String paymentMethod) {
        Specification<OrderInfo> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (orderNo != null && !orderNo.isEmpty()) {
                predicates.add(cb.like(root.get("orderNo"), "%" + orderNo + "%"));
            }
            if (userId != null && !userId.isEmpty()) {
                try {
                    Long userIdLong = Long.parseLong(userId);
                    predicates.add(cb.equal(root.get("userId"), userIdLong));
                } catch (NumberFormatException e) {
                    // 如果userId不是数字，忽略这个条件
                }
            }
            if (userName != null && !userName.isEmpty()) {
                predicates.add(cb.like(root.get("userName"), "%" + userName + "%"));
            }
            if (status != null && !status.isEmpty()) {
                predicates.add(cb.equal(root.get("status"), status));
            }
            if (mealType != null && !mealType.isEmpty()) {
                predicates.add(cb.equal(root.get("mealType"), mealType));
            }
            if (menuDate != null && !menuDate.isEmpty()) {
                predicates.add(cb.equal(root.get("menuDate").as(String.class), menuDate));
            }
            if (paymentMethod != null && !paymentMethod.isEmpty()) {
                predicates.add(cb.equal(root.get("paymentMethod"), paymentMethod));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<OrderInfo> orderPage = orderInfoRepository.findAll(spec, pageable);
        
        // 转换为DTO
        List<OrderInfoDTO> dtoList = orderPage.getContent().stream()
                .map(OrderInfoDTO::fromEntity)
                .collect(Collectors.toList());
        
        return PageResponse.of(dtoList, orderPage.getTotalElements(), size, page);
    }
} 